package cc.rengu.igas.mcps.core.service.trans.stagepay;

import cc.rengu.igas.channel.cups.facade.response.ConsumeResponse;
import cc.rengu.igas.channel.upqc.facade.result.Result;
import cc.rengu.igas.mcps.common.constant.McpsParamConstant;
import cc.rengu.igas.mcps.common.constant.McpsTreeNodeConstant;
import cc.rengu.igas.mcps.common.enums.AcctTypeEnum;
import cc.rengu.igas.mcps.common.enums.McpsAcctTypeEnum;
import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.core.model.AcctAndFeeType;
import cc.rengu.igas.mcps.core.realize.EsbRealSttlePaymentService;
import cc.rengu.igas.mcps.core.realize.PosParamDealService;
import cc.rengu.igas.mcps.core.realize.impl.EsbRealSttlePaymentServiceImpl;
import cc.rengu.igas.mcps.core.realize.impl.PosParamDealServiceImpl;
import cc.rengu.igas.mcps.core.service.base.PayService;
import cc.rengu.igas.mcps.facade.request.InstallmentConsumeRequest;
import cc.rengu.igas.mcps.facade.response.InstallmentConsumeResponse;
import cc.rengu.igas.share.common.dao.RoleAcctInfoMapper;
import cc.rengu.igas.share.common.dao.impl.RoleAcctInfoMapperImpl;
import cc.rengu.igas.share.common.entity.RoleAcctInfo;
import cc.rengu.igas.share.common.util.GlobalEsbUtil;
import cc.rengu.igas.share.core.model.MchntAcctInfo;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;


/**
 * Created by zhangbin on 2020/3/31
 * 分期消费
 */
public class InstallmentConsumeService extends PayService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        InstallmentConsumeRequest installmentConsumeRequest = new InstallmentConsumeRequest();
        ConvertUtil.convertOutput(installmentConsumeRequest);
        return installmentConsumeRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        BizResponse bizResponse = new BizResponse();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        InstallmentConsumeRequest installmentConsumeRequest = (InstallmentConsumeRequest) request;
        //组装报文
        InstallmentConsumeResponse installmentConsumeResponse = new InstallmentConsumeResponse();
        installmentConsumeResponse.setHeader(installmentConsumeRequest.getHeader());
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        String sysSeq = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);

        /*获取账户类型与费率类型*/
        AcctAndFeeType acctAndFeeType = (AcctAndFeeType) xmlTreeUtil.getXmlTreeObjectValue(McpsTreeNodeConstant.ACCT_AND_FEE_TYPE, AcctAndFeeType.class);

        /* TODO 只允许本行贷记卡分期消费 */
        if (!McpsAcctTypeEnum.OWN_CREDIT.getAcctType().equals(acctAndFeeType.getAcctType())) {
            rglog.error("只允许本行贷记卡分期消费!! acctType:{}", acctAndFeeType.getAcctType());
            throw new BizException(RespCodeEnum.ACCT_TYPE_NOT_SUPPORT.getRespCode(), RespCodeEnum.ACCT_TYPE_NOT_SUPPORT.getRespDesc());
        }
        OrderService orderService = new OrderServiceImpl();
        /*获取商户基本信息*/
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(instId, installmentConsumeRequest.getMchntNo());
        if (null == mchntInfo) {
            rglog.error("查询商户信息失败<{}>", installmentConsumeRequest.getMchntNo());
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        //初始化用户订单表
        UserOrderInfo userOrderInfo = initOrderInfoUser(installmentConsumeRequest);
        //初始化商户订单表
        MchntOrderInfo mchntOrderInfo = initOrderInfoMchnt(installmentConsumeRequest, userOrderInfo, acctAndFeeType);

        //支付通道调用
        PayOrderInfo payOrderInfoConsume = initOrderInfoConsume(userOrderInfo, installmentConsumeRequest);

        /*注册用户 商户订单*/
        List<MchntOrderInfo> mchntOrderInfoList = new ArrayList<>();
        mchntOrderInfoList.add(mchntOrderInfo);
        if (!orderService.registerOrderInfo(userOrderInfo, mchntOrderInfoList, payOrderInfoConsume)) {
            rglog.error("订单注册失败!!");
            throw new BizException(RespCodeEnum.REGISTER_ORDER_ERROR.getRespCode(), RespCodeEnum.REGISTER_ORDER_ERROR.getRespDesc());
        }

        // 获取费率信息
        String feeInputModeFlag = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.SPECIAL_FEE_INPUT_MODE);
        //转pin
        String newPin = installmentConsumeRequest.getPin();
        /*调用银数分期消费*/
        if (McpsAcctTypeEnum.OWN_CREDIT.getAcctType().equals(acctAndFeeType.getAcctType())) {
            updcConsume(installmentConsumeRequest, newPin, userOrderInfo, mchntOrderInfo, payOrderInfoConsume, feeInputModeFlag, installmentConsumeResponse);
        }

        /*特殊费率商户交易成功后调用微信进行消息推送*/
        if ("Y".equals(feeInputModeFlag) && TransStatusEnum.TRANS_SUCC.getStatus().equals(payOrderInfoConsume.getTransStatus()) && BizStatusEnum.FINISH.getStatus().equals(payOrderInfoConsume.getBizStatus())) {
//            TransMsgWchatPushService transMsgWchatPushService=new TransMsgWchatPushServiceImpl();
//            String payType="银行卡分期支付";
//            transMsgWchatPushService.financialTransMsgPush(mchntBaseInfo,mchntOrderInfoInstal,payType,installmentConsumeRequest.getHeader());
            int iReturnCode = asynnotify.transactionNotice("MchntTransNoticeService", 1, 0, 0);
            if (0 != iReturnCode) {
                rglog.error("提交交易结果异步通知给商户失败!");
            }
        }

        installmentConsumeResponse.setPayId(sysSeq);
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        bizResponse.setRespCode(payOrderInfoConsume.getRespCode());
        bizResponse.setRespDesc(payOrderInfoConsume.getRespDesc());
        bizResponse.setResult(installmentConsumeResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        InstallmentConsumeResponse installmentConsumeResponse = (InstallmentConsumeResponse) bizResponse.getResult();
        installmentConsumeResponse.setRespCode(bizResponse.getRespCode());
        installmentConsumeResponse.setRespDesc(bizResponse.getRespDesc());
        ConvertUtil.convertInput(installmentConsumeResponse);
    }

    /**
     * 登记支付订单表
     *
     * @param installmentConsumeRequest 请求信息
     * @throws Exception 异常
     */
    private PayOrderInfo initOrderInfoConsume(UserOrderInfo userOrderInfo, InstallmentConsumeRequest installmentConsumeRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = installmentConsumeRequest.getHeader().getInstId();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.SYS_SEQ_NUM);
        String txnNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_NUM);
        String bizType = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.BIZ_TYPE);
        PosParamDealService posParamDealService = new PosParamDealServiceImpl();
        /*获取本行内部渠道户*/
        RoleAcctInfoMapper roleAcctInfoMapper = new RoleAcctInfoMapperImpl();
        RoleAcctInfo roleAcctInfoInfo = roleAcctInfoMapper.selectBankRoleAcctInfoBySettleAcctId(instId, "BANK_PAYCHNL_SUBJECT", instId + McpsParamConstant.DEFAULT_TOP_INST_ID);
        /* 登记支付订单信息 */
        PayOrderInfo payOrderInfo = new PayOrderInfo();
        payOrderInfo.setInstId(instId);
        payOrderInfo.setTxnDate(DateUtil.getCurrentDate());
        payOrderInfo.setTxnTime(DateUtil.getCurrentTime());
        payOrderInfo.setTxnNum(txnNum);
        payOrderInfo.setBizType(bizType);
        payOrderInfo.setSysSeqNum(sysSeqNum);
        payOrderInfo.setMchntNo(installmentConsumeRequest.getMchntNo());
        payOrderInfo.setMchntOrderId(userOrderInfo.getMchntOrderId());
        payOrderInfo.setOrderCcy(AppParamConstant.DEFAULT_ORDER_CCY);
        payOrderInfo.setOrderAmt(userOrderInfo.getOrderAmt());
        if (null != userOrderInfo.getRealPayAmt()) {
            payOrderInfo.setRealPayAmt(userOrderInfo.getRealPayAmt());
        } else {
            payOrderInfo.setRealPayAmt(userOrderInfo.getOrderAmt());
        }
        payOrderInfo.setMsgDstId(ChannelEnum.CUPS.getChannelType());
        /*调用序号*/
        String strIndex = xmlTreeUtil.getXmlTreeStringValue("currentDstCallIndex");
        Integer acctCallIndex = new Integer((StringUtil.isEmptyOrNull(strIndex)) ? "0" : strIndex);
        String dstAcctCallIndex = Integer.toString(acctCallIndex + 1);
        payOrderInfo.setDstCallIndex(acctCallIndex.toString());
        xmlTreeUtil.setXmlTreeStringValue("currentDstCallIndex", dstAcctCallIndex);
        payOrderInfo.setChannelOrderId(GlobalEsbUtil.generateEsbSeqeuenceNumber(instId));
        /*通道标示*/
        payOrderInfo.setMsgDstId(ChannelEnum.CUPS.getChannelType());
        /*支付方式*/
        payOrderInfo.setPayType(PayTypeEnum.STAGE.getPayType());
        /*对账唯一key*/
        payOrderInfo.setChannelReconKey(payOrderInfo.getChannelOrderId());
        /* TODO 通道交易码 */
        payOrderInfo.setDstTxnNum("XXXXXXX");
        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        payOrderInfo.setPayerAcctInfo(installmentConsumeRequest.getPayAcctNo());
        payOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        payOrderInfo.setPayerAcctType(AcctTypeEnum.CREDIT.getAcctType());
        if (null != roleAcctInfoInfo) {
            payOrderInfo.setPayeeAcctInfo(roleAcctInfoInfo.getActualAcct());
        }
        payOrderInfo.setChannelBizType("0000");
        return payOrderInfo;
    }

    /**
     * 初始化商户订单表
     *
     * @param installmentConsumeRequest 请求信息
     * @throws Exception 异常
     */
    private MchntOrderInfo initOrderInfoMchnt(InstallmentConsumeRequest installmentConsumeRequest, UserOrderInfo userOrderInfo, AcctAndFeeType acctAndFeeType) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /*获取商户基本信息*/
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(installmentConsumeRequest.getHeader().getInstId(), installmentConsumeRequest.getMchntNo());
        if (null == mchntInfo) {
            rglog.error("查询商户信息失败<{}>", installmentConsumeRequest.getMchntNo());
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        //获取商户结算账户信息
        MchntAcctInfo mchntAcctInfo = getMchntAcctInfo(installmentConsumeRequest, mchntInfo);
        MchntOrderInfo mchntOrderInfo = new MchntOrderInfo();
        /*内部树复制会把订单状态保存到商户订单信息表*/
        BeanUtil.beanCopy(userOrderInfo, mchntOrderInfo);
        /*设置操作员id*/
        mchntOrderInfo.setUserId(null);
        /*设置商户订单表中业务产品代码*/
        mchntOrderInfo.setBizProdCode(txnInfo.getSrcTxnAuthCfg().getBizProdCode());
        /*收单机构号 */
        mchntOrderInfo.setAcqInstCode(mchntInfo.getSignInstId());
        /*行业类别*/
        mchntOrderInfo.setIndustryType(mchntInfo.getIndustryType());
        /*商户号*/
        mchntOrderInfo.setMchntNo(installmentConsumeRequest.getMchntNo());
        /*若存在 设置连锁商户门店*/
        if (null != mchntInfo.getChainMchntNo()) {
            mchntOrderInfo.setChainMchntNo(mchntInfo.getChainMchntNo());
        }
        /*商户名称*/
        mchntOrderInfo.setMchntName(mchntInfo.getMchntName());
        /*交易币种*/
        mchntOrderInfo.setOrderCcy(AppParamConstant.DEFAULT_ORDER_CCY);
        /*交易金额*/
        mchntOrderInfo.setRealSettleAmt(installmentConsumeRequest.getTransAmt());
        /*实时清算标识*/
        mchntOrderInfo.setRealSettleFlag(mchntInfo.getRealSettleFlag());
        /*设置交易状态*/
        mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        /*设置业务状态*/
        mchntOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        /*创建时间*/
        mchntOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        /*终端号*/
        mchntOrderInfo.setTermNo(installmentConsumeRequest.getTermNo());
        /*分期期数*/
        mchntOrderInfo.setStageNum(installmentConsumeRequest.getStageNum());
        /*分期产品代码*/
        mchntOrderInfo.setProdStageCode(installmentConsumeRequest.getStageCode());
        mchntOrderInfo.setRealSettleFlag(AppParamConstant.NO);

        // 获取费率信息
        String feeInputModeFlag = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.SPECIAL_FEE_INPUT_MODE);
        //非特殊费率商户
        if (!"Y".equals(feeInputModeFlag)) {
            /*调用手续费计算接口*/
            boolean calcResult = mchntService.calcMchntFee(mchntOrderInfo, acctAndFeeType.getFeeType());
            //mod by lizhangtao 由于商户费率信息表中不同的产品存以下三种组合：全特殊费率，全非特殊费率，特殊和非特殊都存在；
            // 且计算手续费时只要存在特殊费率（不管是不是当前产品的）都不实时计算手续费
            // 失败：
            //   1. 返回为空 ||
            //   2. 该商户计算手续费应答中认为非特殊费率商户（全都是非特殊费率），但是没有手续费
            // 成功：(除以上失败)
            //   返回对象非空 && ((返回的FeeInputMode为0 && 无手续费) || (返回的FeeInputMode为非0 && 有手续费))
            if (!calcResult ||
                    (!"0".equals(mchntOrderInfo.getFeeInputMode()) &&
                            null == mchntOrderInfo.getMchntFee())) {
                rglog.error("计算商户手续费失败");
                throw new BizException(RespCodeEnum.CALC_MCHNT_FEE_ERROR.getRespCode(), RespCodeEnum.CALC_MCHNT_FEE_ERROR.getRespDesc());
            }
            if ("0".equals(mchntOrderInfo.getFeeInputMode())) {
                rglog.debug("由于存在了其他产品为特殊计费，因此该商户<{}>被认为是特殊费率商户不计算手续费！！", mchntOrderInfo.getMchntNo());
                mchntOrderInfo.setFeeInputMode("0");
                mchntOrderInfo.setMchntSettleAmt(mchntOrderInfo.getOrderAmt());
            }
        } else {
            rglog.debug("特殊费率商户不计算手续费！！");
            mchntOrderInfo.setFeeInputMode("0");
            mchntOrderInfo.setMchntSettleAmt(mchntOrderInfo.getOrderAmt());
        }

        /*判断是否商户实时清算方式*/
        judeRealTimClearWay(installmentConsumeRequest, mchntInfo, mchntOrderInfo, acctAndFeeType);
        return mchntOrderInfo;
    }

    /**
     * 初始化用户订单表
     *
     * @param installmentConsumeRequest 请求信息
     * @throws Exception 异常
     */
    private UserOrderInfo initOrderInfoUser(InstallmentConsumeRequest installmentConsumeRequest) throws Exception {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        UserOrderInfo userOrderInfo = new UserOrderInfo();
        /*获取机构号*/
        String instId = installmentConsumeRequest.getHeader().getInstId();
        /*获取交易码*/
        String txnNum = installmentConsumeRequest.getHeader().getTxnNum();
        /*获取业务细分*/
        String bizType = installmentConsumeRequest.getHeader().getBizType();
        /*获取源系统标识*/
        String msgSrcId = installmentConsumeRequest.getHeader().getSrcSysId();
        userOrderInfo.setInstId(instId);
        userOrderInfo.setTxnDate(DateUtil.getCurrentDate());
        userOrderInfo.setTxnTime(DateUtil.getCurrentTime());
        userOrderInfo.setTxnNum(txnNum);
        userOrderInfo.setBizType(bizType);
        userOrderInfo.setMsgSrcId(msgSrcId);
        userOrderInfo.setTransChannelId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_CHANNEL_ID));
        userOrderInfo.setMchntOrderId(sysSeqNum);
        userOrderInfo.setOrderDesc("刷卡分期消费");
        userOrderInfo.setSysSeqNum(sysSeqNum);
        userOrderInfo.setOrderCreateTime(DateUtil.getCurrentDateTime("yyyyMMddHHmmss"));
        userOrderInfo.setOrderExpiryTime(DateUtil.getDateByTimeStamp(System.currentTimeMillis() + 5 * 60 * 1000, "yyyyMMddHHmmss"));
        userOrderInfo.setOrderStatus(OrderStatusEnum.INIT.getStatus());
        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        userOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        userOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        userOrderInfo.setOrderAmt(installmentConsumeRequest.getTransAmt());
        userOrderInfo.setFrontSeqNum(installmentConsumeRequest.getHeader().getTraceNo());
        userOrderInfo.setUserId(installmentConsumeRequest.getPayAcctNo());
        return userOrderInfo;
    }

    /*本行贷记卡 通道调用*/
    private void updcConsume(InstallmentConsumeRequest installmentConsumeRequest, String newPin,
                             UserOrderInfo userOrderInfo, MchntOrderInfo mchntOrderInfo,
                             PayOrderInfo payOrderInfoConsume, String feeInputModeFlag,
                             InstallmentConsumeResponse installmentConsumeResponse) throws Exception {
        /*设置dubbo服务*/
        DubboService dubboService = new DubboServiceImpl();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /*初始化订单服务*/
        OrderService orderService = new OrderServiceImpl();
        PosParamDealService posParamDealService = new PosParamDealServiceImpl();
        /*获取商户号*/
        String mchntNo = installmentConsumeRequest.getMchntNo();
        /*获取终端号*/
        String termNo = installmentConsumeRequest.getTermNo();
        /*获取机构号*/
        String instId = installmentConsumeRequest.getHeader().getInstId();
        /*设置银数消费请求报文*/
        /*设置esb通道商户信息*/
        // TODO 分期消费
        // (1) 通讯级失败, 更新订单为失败, 调用营销冲正comboDealService.cancelComboPayment
        // (2) 交易超时, 更新订单为超时.
        // (3) 交易成功,更新交易支付订单交易成功,
        //      判断是否实时清算esbRealSttlePaymentService.esbRealTimeClear/esbRealSttlePaymentService.esbRealSettlePayment 或 非特殊费率商户发起虚拟账户单笔记账acctDealService.virtAcctSingleAdjust
        //      更新商户限额、终端限额、交易限额及笔数 mchntService.addTxnLimitStatis


        /*打印请求报文*/
        /* TODO 调用服务*/
        Result<ConsumeResponse> result = new Result<>();
        ConsumeResponse consumeResponse = new ConsumeResponse();
        consumeResponse.setRespCode(McpsParamConstant.DUBBO_SUCCESS);
        consumeResponse.setRespDesc("交易成功");
        consumeResponse.setSettleDate(DateUtil.getCurrentDate());
        result.setResult(consumeResponse);
        result.setSuccess(true);
        rglog.debug("dubbo调用CUPS消费结果：{}", JSON.toJSONString(result));
        /*调用失败处理*/
        if (null == result || null == result.getResult()
                || (!McpsParamConstant.DUBBO_SUCCESS.equals(result.getResult().getRespCode())
                && !McpsParamConstant.DUBBO_OVERTIME.equals(result.getResult().getRespCode())
                && !McpsParamConstant.COMMUNICATION_OVERTIME.equals(result.getResult().getRespCode()))) {
            /*设置支付订单 订单状态*/
            payOrderInfoConsume.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            payOrderInfoConsume.setBizStatus(BizStatusEnum.FAILED.getStatus());
            /*设置商户订单 订单状态*/
            mchntOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            mchntOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
            /*设置用户订单 订单状态*/
            userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
            if (!orderService.updateOrderInfo(userOrderInfo, Arrays.asList(mchntOrderInfo), payOrderInfoConsume)) {
                rglog.error("订单表更新失败");
                throw new BizException(RespCodeEnum.UPDATE_ORDER_ERROR.getRespCode(), RespCodeEnum.UPDATE_ORDER_ERROR.getRespDesc());
            }
        }
        //调用成功处理
        else if (result.isSuccess() && McpsParamConstant.DUBBO_SUCCESS.equals(result.getResult().getRespCode())) {
            /*通道清算日期*/
            payOrderInfoConsume.setSettleDate(result.getResult().getSettleDate());
            /*设置返回码跟描述*/
            payOrderInfoConsume.setRespCode(result.getResult().getRespCode());
            payOrderInfoConsume.setRespDesc(result.getResult().getRespDesc());
            /*设置支付订单 订单状态*/
            payOrderInfoConsume.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            payOrderInfoConsume.setBizStatus(BizStatusEnum.FINISH.getStatus());
            /*设置商户订单 订单状态*/
            mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            mchntOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
            /*设置用户订单 订单状态*/
            userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
            userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
            /*更新*/
            if (!orderService.updateOrderInfo(userOrderInfo, Arrays.asList(mchntOrderInfo), payOrderInfoConsume)) {
                rglog.error("订单表更新失败");
                throw new BizException(RespCodeEnum.UPDATE_ORDER_ERROR.getRespCode(), RespCodeEnum.UPDATE_ORDER_ERROR.getRespDesc());
            }
            /*插入更新后的商户订单表 到内部树*/
            xmlTreeUtil.setXmlTreeObjectValue(McpsTreeNodeConstant.MCHNT_ORDER_INFO, mchntOrderInfo);
            /*判断是否实时清算*/
            EsbRealSttlePaymentService esbRealSttlePaymentService = new EsbRealSttlePaymentServiceImpl();
            if (AppParamConstant.YES.equals(mchntOrderInfo.getRealSettleFlag())) {
                if ("00".equals(mchntOrderInfo.getRealSettleType())) {
                    esbRealSttlePaymentService.esbRealTimeClear(mchntOrderInfo, payOrderInfoConsume, installmentConsumeRequest.getHeader());
                } else {
                    esbRealSttlePaymentService.esbRealSettlePayment(mchntOrderInfo, payOrderInfoConsume, installmentConsumeRequest.getHeader());
                }
            }
            //更新商户限额、终端限额、交易限额及笔数
            MchntService mchntService = new MchntServiceImpl();
            mchntService.updateMchntTransLimit(mchntOrderInfo);
        }
        //调用超时处理
        else {
            /*设置返回码跟描述*/
            payOrderInfoConsume.setRespCode(result.getResult().getRespCode());
            payOrderInfoConsume.setRespDesc(result.getResult().getRespDesc());
            /*设置支付订单 订单状态*/
            payOrderInfoConsume.setTransStatus(TransStatusEnum.TRANS_TIMEOUT.getStatus());
            /*设置商户订单 订单状态*/
            mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_TIMEOUT.getStatus());
            /*设置用户订单 订单状态*/
            userOrderInfo.setTransStatus(TransStatusEnum.TRANS_TIMEOUT.getStatus());
            if (!orderService.updateOrderInfo(userOrderInfo, Arrays.asList(mchntOrderInfo), payOrderInfoConsume)) {
                rglog.error("订单表更新失败");
                throw new BizException(RespCodeEnum.UPDATE_ORDER_ERROR.getRespCode(), RespCodeEnum.UPDATE_ORDER_ERROR.getRespDesc());
            }
        }

        /*设置返回码 返回信息*/
        if (null == result || !result.isSuccess()) {
            installmentConsumeResponse.setRespCode(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
            installmentConsumeResponse.setRespDesc(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
        } else {
            installmentConsumeResponse.setRespCode(result.getResult().getRespCode());
            installmentConsumeResponse.setRespDesc(result.getResult().getRespDesc());
            installmentConsumeResponse.setPayId(payOrderInfoConsume.getSysSeqNum());
            installmentConsumeResponse.setSettleDate(result.getResult().getSettleDate());
            installmentConsumeResponse.setIcData(result.getResult().getIcData());
        }


    }

    /*获取实时入账最小金额*/
    private String getRealTimeClearAmt(String instId) throws Exception {
        String paramType = "MCHNT_SERVICE";
        String paramKey = "D0_ACCOUNTING_MIN_AMT";
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(instId, paramType, paramKey);
        if (null == sysParam) {
            rglog.info("实时入账最小金额未配置,使用默认金额");
            return McpsParamConstant.DEFAULT_REAL_TIME_PAY_MIN_AMT;
        } else {
            return sysParam.getParamValue();
        }
    }

    /*判断是否商户实时清算方式*/
    private void judeRealTimClearWay(InstallmentConsumeRequest installmentConsumeRequest, MchntInfo mchntInfo, MchntOrderInfo mchntOrderInfo, AcctAndFeeType acctAndFeeType) throws Exception {
        /*获取结算账户信息*/
        MchntAcctInfo mchntAcctInfo = getMchntAcctInfo(installmentConsumeRequest, mchntInfo);
        /* 获取实时入账最低金额*/
        String minAmt = getRealTimeClearAmt(mchntOrderInfo.getInstId());
        /*判断交易金额是否大于实时入账最低金额*/
        if (AmountUtil.compare(mchntOrderInfo.getRealSettleAmt(), minAmt) != -1) {
            /* 实时清算标识 、结算方式*/
            if ("Y".equals(mchntInfo.getRealSettleFlag()) && (McpsAcctTypeEnum.OWN_DEBIT.getAcctType().equals(acctAndFeeType.getAcctType()) || McpsAcctTypeEnum.OWN_CREDIT.getAcctType().equals(acctAndFeeType.getAcctType()))) {
                mchntOrderInfo.setRealSettleFlag("Y");
                mchntOrderInfo.setRealSettleType("00");
            } else if ("D0".equals(mchntAcctInfo.getSettleType()) && !"Y".equals(mchntInfo.getRealSettleFlag())) {
                mchntOrderInfo.setRealSettleFlag("Y");
                mchntOrderInfo.setRealSettleType("99");
            } else {
                mchntOrderInfo.setRealSettleFlag("N");
            }
        }
    }

    /*获取商户结算账户信息*/
    private MchntAcctInfo getMchntAcctInfo(InstallmentConsumeRequest request, MchntInfo mchntInfo) throws Exception {
        String mchntNo = mchntInfo.getMchntNo();
        /*判断商户是否为独立清算商户*/
        if (!"Y".equals(mchntInfo.getIndependentDataFlag()) && "11".equals(mchntInfo.getMchntType())) {
            mchntNo = mchntInfo.getChainMchntNo();
        }
        MchntService mchntService = new MchntServiceImpl();
        List<MchntAcctInfo> mchntAcctInfoList = mchntService.getMchntAcctInfo(request.getHeader().getInstId(), mchntNo);
        Optional<MchntAcctInfo> mchntAcctInfoOpt = mchntAcctInfoList.stream().filter(item -> item.getFundType().equals("00")).findFirst();
        return mchntAcctInfoOpt.orElse(null);
    }
}